package model

import (
	"time"

	"github.com/pkg/errors"
	"gorm.io/gorm"
)

type TaskLog struct {
	ID        uint      `gorm:"column:log_id;primaryKey;autoIncrement" json:"id"`     // 日志id
	TaskID    uint      `gorm:"column:task_id;not null" json:"task_id"`               // 关联的任务id
	UpdatedBy string    `gorm:"column:updated_by;type:varchar(64)" json:"updated_by"` // 更新者
	CreatedAt time.Time `gorm:"column:created_at" json:"created_at"`
	UpdatedAt time.Time `gorm:"column:updated_at" json:"updated_at"`
	Content   string    `gorm:"column:content;type:text" json:"content"`                // 更新内容
	AnnexUrls string    `gorm:"column:annex_urls;type:varchar(5000)" json:"annex_urls"` // 附件集合
}

func (t *TaskLog) Create(tx *gorm.DB) error {
	result := tx.Create(t)
	if result.Error != nil {
		return errors.New("创建任务日志失败")
	}
	return nil
}

// 获取任务日志
func (t *TaskLog) Get(tx *gorm.DB, id any) (*TaskLog, error) {
	result := tx.Model(t).First(t, id)
	if result.Error != nil {
		return nil, errors.New("获取任务日志失败")
	}
	return t, nil
}

// 获取任务日志列表
func (t *TaskLog) List(tx *gorm.DB, taskID any) ([]*TaskLog, error) {
	var logs []*TaskLog
	result := tx.Model(t).Where("task_id = ?", taskID).Order("create_time DESC").Find(&logs)
	if result.Error != nil || errors.Is(result.Error, gorm.ErrRecordNotFound) {
		return nil, errors.New("获取任务日志列表失败")
	}
	return logs, nil
}
